package com.tencent.hummingbird.portal.service.impl;

import cn.hutool.core.util.ArrayUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.tencent.hummingbird.portal.exception.ServiceException;
import com.tencent.hummingbird.portal.mapper.*;
import com.tencent.hummingbird.portal.pojo.*;
import com.tencent.hummingbird.portal.service.IQuestionService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tencent.hummingbird.portal.service.ITagService;
import com.tencent.hummingbird.portal.service.IUserService;
import com.tencent.hummingbird.portal.vo.AskVO;
import com.tencent.hummingbird.portal.vo.EditQuestionVO;
import com.tencent.hummingbird.portal.vo.QuestionVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author yxb
 * @since 2024-01-10
 */
@Service
@Slf4j
public class QuestionServiceImpl extends ServiceImpl<QuestionMapper, Question> implements IQuestionService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private QuestionMapper questionMapper;
    @Autowired
    private ITagService tagService;
    @Override
    public PageInfo<Question> getMyQuestions(String username,Integer pageNum,Integer pageSize) {
        User user = userMapper.findUserByUsername(username);
        QueryWrapper<Question> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",user.getId());
        queryWrapper.eq("delete_status",0);
        queryWrapper.orderByDesc("createtime");
        PageHelper.startPage(pageNum,pageSize);
        List<Question> questions = questionMapper.selectList(queryWrapper);
        Map<String, Tag> tagMap = tagService.getNameToTagMap();
        for(Question question : questions){
             String[] tagNames = question.getTagNames().split(",");
             List<Tag> tags = new ArrayList<>();
             for(String tagName : tagNames){
                 Tag t = tagMap.get(tagName);
                 tags.add(t);
             }
             question.setTags(tags);
        }
        return new PageInfo<Question>(questions);
    }
    @Autowired
    private QuestionTagMapper questionTagMapper;
    @Autowired
    private IUserService userService;
    @Autowired
    private UserQuestionMapper userQuestionMapper;
    @Override
    @Transactional
    public void saveQuestion(QuestionVO questionVO, String userName) {
        User user = userMapper.findUserByUsername(userName);
        Question question = new Question();
        question.setTitle(questionVO.getTitle());
        question.setContent(questionVO.getContent());
        question.setUserId(user.getId());
        question.setUserNickName(user.getNickname());
        String[] tags = questionVO.getSelectedTags();
        /*String tagNames = "";
        for (String tag : tags){
            tagNames+=tag+",";
        }
        tagNames = tagNames.substring(0, tagNames.lastIndexOf(","));*/
        StringBuilder stringBuilder = new StringBuilder("");
        for (String tagName : tags){
            stringBuilder.append(tagName).append(",");
        }
        String tagNames = stringBuilder.deleteCharAt(stringBuilder.length()-1).toString();
        question.setTagNames(tagNames);
        question.setStatus(0)
                .setDeleteStatus(0)
                .setPageViews(0)
                .setCreatetime(LocalDateTime.now())
                .setPublicStatus(0);
        int num = questionMapper.insert(question);
        if(num!=1){
            throw ServiceException.busy();
        }
        log.info("insert question:{}",question);

        /**
         * 从questionVO中取得标签名称数组
         * 遍历数组依次查询tag对象
         * 从而获得tag-id
         * 与question-id结合插入到关系表中
         */
         Map<String,Tag> tagMap = tagService.getNameToTagMap();
         for(String tagName : questionVO.getSelectedTags()){
             Tag tag = tagMap.get(tagName);
             QuestionTag questionTag = new QuestionTag();
             questionTag.setQuestionId(question.getId());
             questionTag.setTagId(tag.getId());
             int num2 = questionTagMapper.insert(questionTag);
             if(num2!=1){
                 throw ServiceException.busy();
             }
             log.info("insert quest_tag:{}",questionTag);
         }

         Map<String,User> teacherMap =  userService.getTeacherMap();
         for(String nickName :  questionVO.getSelectedTeachers() ){
             User teacher =teacherMap.get((nickName));
             UserQuestion userQuestion = new UserQuestion();
             userQuestion.setQuestionId(question.getId());
             userQuestion.setUserId(teacher.getId());
             userQuestion.setCreatetime(LocalDateTime.now());
             int num3 = userQuestionMapper.insert(userQuestion);
             if(num3!=1){
                 throw ServiceException.busy();
             }
             log.info("insert user_question:{}",userQuestion);
         }
    }

    @Override
    public Integer countQuestionsByUserId(Integer userId) {
        //根据泛型来确定查询那张表
        QueryWrapper<Question> query = new QueryWrapper();
        query.eq("user_id",userId);
        query.eq("delete_status",0);
        int count = questionMapper.selectCount(query);
        return count;
    }

    @Override
    public PageInfo<Question> getQuestionsByTeacherName(String teacherName, Integer pageNum, Integer pageSize) {
        User teacher = userMapper.findUserByUsername(teacherName);
        if(teacher == null){
            throw ServiceException.unprocesabelEntity("没有获取到老师信息");
        }
        PageHelper.startPage(pageNum,pageSize);
        List<Question> questions =  questionMapper.findTeacherQuestions(teacher.getId());
        Map<String, Tag> tagMap = tagService.getNameToTagMap();
        for(Question question : questions){
            String[] tagNames = question.getTagNames().split(",");
            List<Tag> tags = new ArrayList<>();
            for(String tagName : tagNames){
                Tag t = tagMap.get(tagName);
                tags.add(t);
            }
            question.setTags(tags);
        }
        PageInfo<Question> pageInfo = new PageInfo<>(questions);

        return pageInfo;
    }

    @Override
    public Question getQuestionById(Integer id) {
        Question question = questionMapper.selectById(id);
        String[] tagNames = question.getTagNames().split(",");
        Map<String,Tag> tags = tagService.getNameToTagMap();
        for (String tagName : tagNames){
            Tag tag = tags.get(tagName);
            question.getTags().add(tag);
        }
        return question;
    }

    @Override
    public PageInfo<AskVO> getMyAskByUserName(String userName,Integer pageNum,Integer pagesize) {
        User user = userMapper.findUserByUsername(userName);
        PageHelper.startPage(pageNum,pagesize);
        List<AskVO> asks = questionMapper.findMyAsk(user.getId());
        PageInfo<AskVO> pageInfo = new PageInfo(asks);
        return pageInfo;
    }

    @Override
    public Integer updateViewsById(Integer questionId) {
        Integer views = questionMapper.getViewsById(questionId);
        views++;
        log.info("views:{}",views);
        Integer result = questionMapper.updateViewsById(views,questionId);
        return  result;
    }

    @Override
    public Question selectQuestionById(Integer id) {
       Question question =  questionMapper.getQuestionById(id);
       return question;
    }

    @Autowired
    private TagMapper tagMapper;
    @Override
    @Transactional
    public void updateQuestion(EditQuestionVO editQuestionVO) {
        //修改question表
        Question question = questionMapper.getQuestionById(editQuestionVO.getQuestionId());
        String[] tags = editQuestionVO.getSelectedTags();
        String[] teachers = editQuestionVO.getSelectedTeachers();
        /*String tag = "";
        for (int i = 0; i < tags.length; i++) {
            tag += tags[i]+",";
        }
        tag = tag.substring(0, tag.lastIndexOf(","));*/
        String tagNames = ArrayUtil.join(tags,",");
        question.setTagNames(tagNames)
                .setTitle(editQuestionVO.getTitle())
                .setContent(editQuestionVO.getContent())
                .setModifytime(LocalDate.now());
        log.info("question:{}" ,question);
        int num = questionMapper.updateById(question);
        if(num!=1){
            throw ServiceException.busy();
        }
        //修改question_tag表
        questionTagMapper.deleteByQuestionId(question.getId());
        for (int i = 0; i < tags.length; i++) {
            int tagId = tagMapper.selectTagByName(tags[i]);
            QuestionTag questionTag = new QuestionTag();
            questionTag.setTagId(tagId);
            questionTag.setQuestionId(question.getId());
            int num1 = questionTagMapper.insert(questionTag);
            if(num1!=1){
                throw ServiceException.busy();
            }
        }
        //修改user_question表
        userQuestionMapper.deleteByQuestionId(question.getId());
        for (int i = 0; i < teachers.length; i++) {
             User user = userMapper.findUserByUserNickName(teachers[i]);
             UserQuestion userQuestion = new UserQuestion();
             userQuestion.setQuestionId(question.getId())
                         .setUserId(user.getId())
                         .setCreatetime(LocalDateTime.now());
             int num2 = userQuestionMapper.insert(userQuestion);
             if(num2!=1){
                 throw ServiceException.busy();
             }
        }
    }
    @Autowired
    private AnswerMapper answerMapper;
    @Override
    public PageInfo<Question> selectHostQuestions(Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum,pageSize);
        List<Question> questions =  questionMapper.selectHostQuestion();
        for (int i = 0; i < questions.size(); i++) {
            Question question = questions.get(i);
            int answer =  answerMapper.countAnswerByQuestionId(question.getId());
            question.setAnswers(answer);
        }
        PageInfo<Question> pageInfo = new PageInfo<>(questions);
        return pageInfo;
    }

    @Override
    public PageInfo<Question> selectWork(String teacherName, Integer status,Integer pageNum,Integer pageSize) {
        User user = userMapper.findUserByUsername(teacherName);
        PageHelper.startPage(pageNum,pageSize);
        List<Question> questions = questionMapper.selectWorks(user.getId(),status);
        log.info("questions:{}",questions);
        PageInfo<Question> pageInfo = new PageInfo<>(questions);
        return pageInfo;
    }

    @Override
    public EditQuestionVO getEditQuestionVOById(Integer id) {
        Question question = this.getQuestionById(id);
        List<User> teachers = this.getTeachersById(id);
        EditQuestionVO editQuestionVO = new EditQuestionVO();
        List<Tag> tags = question.getTags();
        String[] selectedTags = new String[tags.size()];
        for (int i = 0; i < tags.size(); i++) {
            selectedTags[i] = tags.get(i).getName();
        }
        String[] selectedTeachers = new String[teachers.size()];
        for (int i = 0; i < teachers.size(); i++) {
            selectedTeachers[i] = teachers.get(i).getNickname();
        }
        editQuestionVO.setQuestionId(question.getId()).setContent(question.getContent())
                        .setTitle(question.getTitle())
                        .setSelectedTags(selectedTags)
                        .setSelectedTeachers(selectedTeachers);
        return editQuestionVO;
    }

    @Override
    public List<User> getTeachersById(Integer id) {
        List<User> users = questionMapper.getTeacherById(id);
        return users;
    }

}
